import 'dart:convert';

import 'package:elephant_fish/TRTCLiveRoomDemo/model/TRTCLiveRoom.dart';
import 'package:elephant_fish/model/gift_entity.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class OneGift extends StatefulWidget {
  final GiftEntity giftEntity;
  const OneGift({Key key, this.giftEntity}) : super(key: key);

  @override
  _OneGiftState createState() => _OneGiftState();
}
int id = -1;
bool isSelected = false;
class _OneGiftState extends State<OneGift> {
  bool selected = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }



  @override
  Widget build(BuildContext context) {

    return InkWell(
        onTap: (){
          if(id == -1 || id == widget.giftEntity.id){
            if(isSelected){
              unSaveSelectedGift();
            }else{
              saveSelectedGift();
            }
          }
        },
        child: Column(
          children: [
            Container(
               decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(1.0)),
                border: selected ?  Border.all(width: 1, color: Color(0xfffc3f72)) : Border.all(width: 1)
              ),
              child: Image.network('http://119.28.131.94:82' + widget.giftEntity.icon,width: SizeUtil.px(136),height: SizeUtil.px(136),),
            ),
            SizedBox(height: SizeUtil.px(5),),
            Text(widget.giftEntity.name,style: TextStyle(fontSize: SizeUtil.px(22),color: Color(0xffffffff)),),
            SizedBox(height: SizeUtil.px(4),),

            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset('assets/images/rank_money.png',width: SizeUtil.px(19.95),height: SizeUtil.px(20.52),),
                SizedBox(width: SizeUtil.px(14),),
                Text(widget.giftEntity.gold.toString(),style: TextStyle(fontSize: SizeUtil.px(20),color: Color(0xffffffff)),),
              ],
            ),
          ],
        ),
    );

  }

  Future<void> saveSelectedGift() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    prefs.setString('GIFTINFO', jsonEncode(widget.giftEntity.toJson()));
    setState(() {
      id = widget.giftEntity.id;
      isSelected = true;
      selected = true;
    });
  }

  Future<void> unSaveSelectedGift() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('GIFTINFO', '');
    setState(() {
      id = -1;
      isSelected = false;
      selected = false;
    });
  }

  void init() {
    if(id == widget.giftEntity.id){
      setState(() {
        selected = true;
      });
    }else{
    setState(() {
      selected = false;
    });
    }
  }
}
